﻿using System;
using System.Windows.Forms;
using ProjectDeployment.Model;
using System.Runtime.InteropServices;
using System.Diagnostics;
using ProjectDeployment.Loggers;

namespace ProjectDeployment
{
    static class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AllocConsole();

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool FreeConsole();

        [DllImport("kernel32", SetLastError = true)]
        static extern bool AttachConsole(int dwProcessId);

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();


        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            var projectsInstance = new Projects();
            var logger = Logger.instance;
            args = new string[1];
            args[0] = "-f";
            
            
            if(args.Length > 0)
            {
                var ptr = GetForegroundWindow();
                int u;
                GetWindowThreadProcessId(ptr, out u);
                var process = Process.GetProcessById(u);

                if (process.ProcessName == "cmd")    //Is the uppermost window a cmd process?
                {
                    AttachConsole(process.Id);
                }
                else
                {
                    //no console AND we're in console mode ... create a new console.
                    AllocConsole();
                }

                var consoleLogger = new ConsoleLogger();

                logger.RegisterObserver(consoleLogger);

                if (args[0] == "-f")
                {
                    logger.AddLogMessage("Running for the first time!");
                    //projectsInstance.UninstallProjects(projectsInstance.ProjectsList);
                    //projectsInstance.InstallProjects(projectsInstance.ProjectsList);
                    projectsInstance.CopyOriginalConfigFiles(projectsInstance.ProjectsList);
                }

                if (args[0] == "-n")
                {
                    logger.AddLogMessage("Running the Normal mode!");
                    projectsInstance.CopyConfigFiles(projectsInstance.ProjectsList);
                }

                FreeConsole();
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new ProjectDeployment());
            }
        }
    }
}
